import math

from django.contrib.auth.hashers import check_password
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from app01.models import User
from app01.sers import *


class UserView(APIView):
    def post(self,request):
        ser=UserSer(data=request.data)
        if ser.is_valid():
            # ser.save()
            return Response({'msg':'添加成功'})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败','errors': ser.errors})



class LoginView(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        # print(username)
        # print(password)
        user=User.objects.filter(username=username).first()
        if user and check_password(password,user.password):
            return Response({'msg':'登陆成功','status':200,'uid':user.id})
        return Response({'msg':'登录失败','status':400})

    def get(self,request):
        user_num=int(request.GET.get('num',1))
        user_size=5
        queryset=User.objects.all()[(user_num-1)*user_size:user_size*user_num]                   #每个页面几条数据
        count=User.objects.count()              #总页面长度
        size=math.ceil(count/user_size)               #总共几页

        ser=LoginSer(queryset,many=True)
        print(ser.data)

        resp={'data':ser.data,'user_list':[x for x in range(1,size+1)]}            #循环返回字典
        print(resp)
        return Response(resp)

